﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using MAntLibrary;

namespace MAnt3.dll
{
    class Hitec : IDodavatel
    {
        #region Property
        public string nextLine = "\r\n";
        string[] _DostupnostArr = new string[]{"A","B"};
        string[] _DostupnostNazevArr = new string[] {"Skladem", "Není na skladu"};
        string[] _DostupnostPopisArr = new string[] {"Zboží je skladem", "Zboží není na skladu" };

        private IOproudy ioproudy;
        public IOproudy Ioproudy
        {
            get
            {
                return ioproudy;
            }
            set
            {
                ioproudy = value;
            }
        }

        public string[] GetDostupnostNazev()
        {
            return _DostupnostNazevArr;
        }
        #endregion

        #region Constructor
        
        public Hitec(IOproudy io)
        {
            Ioproudy = io;
        }

        #endregion

        public List<ZboziNetDirect> CtiXml(XmlNode root, FileInfo file, Dodavatel dodavatel)
        {
            ZboziNetDirect item;
            List<ZboziNetDirect> result = new List<ZboziNetDirect>();

            using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.FullName + ";Extended Properties=Excel 8.0"))
            {
                try
                {
                    con.Open();
                    string listname = "List1";

                    //Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference
                    DataSet myDataSet = new DataSet();
                    OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + listname + "$]", con);
                    myCommand.Fill(myDataSet);
                    con.Close();
                    //richTextBox1.AppendText("\nDataSet Filled");

                    //Travers through each row in the dataset
                    foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)
                    {
                        Object[] cells = myDataRow.ItemArray;
                        item = new ZboziNetDirect();
                        item.IdZbozi = myDataRow.ItemArray[0].ToString();
                        item.KodZbozi = myDataRow.ItemArray[0].ToString();
                        item.JmenoVyrobce = myDataRow.ItemArray[1].ToString();
                        item.JmenoVyrobku = myDataRow.ItemArray[2].ToString() + " " + myDataRow.ItemArray[3].ToString(); ;
                        
                        item.setVarianty(myDataRow.ItemArray[4].ToString().Split('/'));
                        
                        // Velikost
                        item.setVelikost(myDataRow[5].ToString());

                        // DOSTUPNOST - pocet kusu
                        if (NastavDostupnost(myDataRow[6].ToString()))
                        {
                            item.Dostupnost = _DostupnostArr[0];
                            item.DostupnostNazev = _DostupnostNazevArr[0];
                            item.DostupnostPopis = _DostupnostPopisArr[0];
                        }
                        else
                        {
                            item.Dostupnost = _DostupnostArr[1];
                            item.DostupnostNazev = _DostupnostNazevArr[1];
                            item.DostupnostPopis = _DostupnostPopisArr[1];
                        }

                        item.JednotkaParametru = myDataRow[7].ToString();
                        item.PuvodniCena = myDataRow.ItemArray[8].ToString();
                        item.setNovaCena(dodavatel.SlevaProDodavatele);

                        // Musim rozhodnout podle nazvu,
                        // jestli ten produkt neexistuje a ma jen jine parametry
                        //if (!IsExist(item, ref result))
                        //{
                            result.Add(item);
                        //}
                    }
                }
                catch (Exception ex)
                {
                    //label8.Content = "Chybný soubor";
                    return result;
                }
            }

            // aktualizuji pocet polozek
            //MainWindow.PocetPolozek = MainWindow.NactenySeznam.Count;
            return result;
        }

        private bool IsExist(ZboziNetDirect newItem, ref List<ZboziNetDirect> list)
        {
            int index = 0;
            int delkaNazvu = newItem.JmenoVyrobku.Length;
            int tolerovanaShoda = (int)(delkaNazvu * 0.7);
            foreach (ZboziNetDirect item in list)
            {
                if (item.JmenoVyrobku.Length <= tolerovanaShoda) 
                {
                    continue;
                }

                if (item.JmenoVyrobku.Substring(0, tolerovanaShoda).Equals(newItem.JmenoVyrobku.Substring(0, tolerovanaShoda)))
                {
                    list[index].setVarianty(newItem.getVarianty());
                    list[index].setVelikost(newItem.getVelikost());

                    return true;
                }
                index++;
            }
            return false;
        }

        private bool NastavDostupnost(string value)
        {
            if (string.IsNullOrEmpty(value)) { return false; }
            if (Char.IsDigit(value[0]))
            {
                int i = Convert.ToInt32(value);
                if (i > 0) { return true; }
                else { return false; }
            }
            else
            {
                if (char.IsDigit(value[1]))
                {
                    int ii = Convert.ToInt32(value.Substring(1,value.Length-1));
                    if (ii > 0) { return true; }
                    else { return false; }
                }
                else
                {
                    return false;
                }
            }
        }

        public string ZobrazInformace(List<ZboziNetDirect> list, int pocitadlo)
        {
            string result = string.Empty;

            foreach (string i in list[pocitadlo].getVarianty())
            {
                result += i+"\n";
            }

            result += list[pocitadlo].getVelikost(true);

            return result;
        }

        public void UlozData(List<ZboziNetDirect> list, int pocitadlo, ref ZboziNetDirect noveZbozi)
        {
            
        }

        public void GenerujParametry(string path, string znacka, List<ZboziNetDirect> list, string timeStamp)
        {
            string filename = "\\" + znacka + "-" + "Parametry" + "-" + timeStamp + ".xml";
            FileStream fs = new FileStream(path + filename, FileMode.Create);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            XmlWriter w = XmlWriter.Create(fs, settings);

            w.WriteStartDocument();
            w.WriteStartElement("parametry");
            w.WriteAttributeString("manufacturer", "netdirect");
            w.WriteAttributeString("version", "09.01");
            w.WriteAttributeString("bVlozit", "1");
            w.WriteAttributeString("bOpravit", "1");
            w.WriteAttributeString("bKompletniXml", "1");
            w.WriteAttributeString("sIdZbozi", "sKodZbozi");

            //cyklus
            // opravit seznami a dod2lat ks a pary - varianty a velikosti
            foreach (ZboziNetDirect zbozi in list)
            {
                foreach (string varianta in zbozi.getVarianty())
                {
                    // BARVY
                    w.WriteStartElement("zaznam");

                    w.WriteElementString("sJmenoParametru", "barvy");

                    w.WriteElementString("sJednotkaParametru", zbozi.JednotkaParametru);
                    w.WriteElementString("sPopisParametru", "barva");
                    w.WriteElementString("sIdZbozi", zbozi.IdZbozi);

                    w.WriteElementString("sHodnotaParametru", varianta); //100-bila


                    w.WriteElementString("bVypnout", "0");

                    w.WriteElementString("bHlavniHodnota", "1"); //1
                    w.WriteElementString("nPoradiZobrazeniParametru", "100");

                    w.WriteElementString("nPoradiZobrazeniHodnoty", "1"); //1
                    w.WriteElementString("bVyberovyParametr", "1");

                    w.WriteEndElement();
                }
            }

            w.WriteEndElement();
            w.WriteEndDocument();
            w.Flush();
            fs.Close();
        }

        public void VytvorXML(string destinationPath, string jmenoDodavatele, List<ZboziNetDirect> UpravenySeznam)
        {
            string timeStamp = DateTime.Now.ToString("yyyy-MM-dd Hmm");
            string filename = "FastCentrik2" + "-" + timeStamp + ".xml";

            FileStream fs = new FileStream(Path.Combine(destinationPath, filename), FileMode.Create);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            



            XDocument Xdocument = new XDocument(new XDeclaration("1.0", "UTF-8", "standalone"));
            XmlWriter writer = XmlWriter.Create(fs, settings);


            //SkladovaDostupnost(writer, UpravenySeznam);
            Zbozi(writer, UpravenySeznam);

            

            
            writer.WriteEndDocument();
            writer.Flush();
            fs.Close();
        }

        private void SkladovaDostupnost(XmlWriter w, List<ZboziNetDirect> UpravenySeznam)
        {
            //string namespaces = string.Format("o:StockAvailabilities xmlns:o="http://schemas.netdirect.cz/data/scl/StockAvailability" xmlns:sql="urn:schemas-microsoft-com:xml-sql");
            //w.WriteStartElement(namespaces,);
            foreach (ZboziNetDirect zbozi in UpravenySeznam)
            {
                w.WriteStartElement("zaznam");

                w.WriteElementString("sJmenoParametru", "barvy");

                w.WriteElementString("sJednotkaParametru", zbozi.JednotkaParametru);
                w.WriteElementString("sPopisParametru", "barva");
                w.WriteElementString("sIdZbozi", zbozi.IdZbozi);

                //w.WriteElementString("sHodnotaParametru", varianta); //100-bila


                w.WriteElementString("bVypnout", "0");

                w.WriteElementString("bHlavniHodnota", "1"); //1
                w.WriteElementString("nPoradiZobrazeniParametru", "100");

                w.WriteElementString("nPoradiZobrazeniHodnoty", "1"); //1
                w.WriteElementString("bVyberovyParametr", "1");

                w.WriteEndElement();
            }
        }

        private void Zbozi(XmlWriter writer, List<ZboziNetDirect> UpravenySeznam)
        {
            writer.WriteStartElement("Commodities","o");
            
            foreach (ZboziNetDirect zbozi in UpravenySeznam)
            {
                writer.WriteStartElement("Commodity", "y0");
                    writer.WriteAttributeString("nVariantMaskId", "1");
                    writer.WriteAttributeString("sCode", "S24A300H");
                    writer.WriteAttributeString("nStartingQuantity", "1");
                    writer.WriteAttributeString("nMinQuantity", "1");
                    writer.WriteAttributeString("bFreeShipping", "0");
                    writer.WriteAttributeString("bPurchasedSeparately", "1");
                    writer.WriteAttributeString("nShippingWeight", "10");
                    writer.WriteAttributeString("nQuantityInStock", "1");
                    writer.WriteAttributeString("bMaster", "0");
                    writer.WriteAttributeString("nOrder", "1");
                    writer.WriteAttributeString("bSet", "0");
                    writer.WriteAttributeString("bTemplate", "0");
                    writer.WriteAttributeString("bDisabled", "0");
                    writer.WriteAttributeString("sExternalRecordId", "1D84C73D-7B74-4079-8CFC-D18B149112BC");
                    writer.WriteAttributeString("bAllSlaveDisabled", "0");
                    writer.WriteAttributeString("bDeleted", "0"); 
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
    }
}
